<template>
  <div
    class="panel"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
  >
    <panel-title title="规则列表"></panel-title>
    <div class="panel-body">
      <!--搜索框-->
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="">
          <el-input v-model="searchRuleName" placeholder="规则名称"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="searchCrawlDate"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
          >
          </el-date-picker>
        </el-form-item>
        <el-button @click="cleanSearch"
          ><i class="fa el-icon-close"></i>&nbsp;清空</el-button
        >
        <el-button type="primary" @click="getWarningPageData"
          ><i class="fa fa-search"></i>&nbsp;查询</el-button
        >
        <!--<el-button type="warning" @click="exportExcel"><i class="fa fa-download"></i>&nbsp;导出</el-button>-->
      </el-form>
      <el-table size="mini" :data="clients.data" border style="width: 100%">
        <el-table-column
          prop="ruleName"
          label="规则名称"
          width="180px"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="description"
          label="规则描述"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="sentiment"
          label="情感"
          width="80px"
          align="center"
        >
          <template slot-scope="scope">
            {{ translateSentiment(scope.row.sentiment) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="type"
          label="舆情类型"
          width="120px"
          align="center"
        >
          <template slot-scope="scope">
            <span
              v-for="(item, index) in scope.row.type.split(',')"
              :key="index"
            >
              <el-tag type="success">{{ item }}</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="hotIndex"
          label="热度"
          width="100px"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="email"
          label="预警邮箱"
          width="100px"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="时间"
          width="150px"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ dateFormat(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="autoRun"
          label="自动运行"
          width="120px"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.autoRun"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeAutoRun(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="操作" width="180px" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="runRule(scope.row.id)"
              >运行</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="updateRule(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="deleteRule(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="clients.currentPageNo"
          :page-sizes="[10, 50, 100, 200]"
          :page-size="clients.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="clients.total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import soldsChart from "../../components/chart/soldsChart";
import { panelTitle } from "components";
import moment from "moment";

export default {
  name: "warning",
  data() {
    return {
      clients: {
        total: 0,
        pageSize: 10,
        currentPageNo: 1,
        data: [],
      },
      searchRuleName: null,
      searchCrawlDate: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  components: {
    soldsChart,
    panelTitle,
  },
  created() {
    this.getWarningPageData();
  },
  methods: {
    //获取数据
    getWarningPageData() {
      this.loading = true;
      this.$fetch.apiWarning
        .getWarningPageData({
          //查询参数
          pageSize: this.clients.pageSize,
          pageNo: this.clients.currentPageNo,
          ruleName: this.searchRuleName,
          startDate: this.searchCrawlDate[0],
          endDate: this.searchCrawlDate[1],
        })
        .then(({ data: data }) => {
          this.clients = data;
          this.clients.data.forEach(e => {
            e.autoRun = Boolean(e.autoRun)
          })
          this.loading = false;
          console.log(this.clients);
        });
    },
    handleSizeChange(val) {
      this.clients.pageSize = val;
      this.getWarningPageData();
    },
    handleCurrentChange(val) {
      this.clients.currentPageNo = val;
      this.getWarningPageData();
    },
    translateSentiment(sentiment) {
      if (sentiment == 0) {
        return "负面";
      } else if (sentiment == 2) {
        return "正面";
      } else {
        return "中立";
      }
    },
    openNewPage(url) {
      window.open(url);
    },
    dateFormat(dateTime) {
      if (dateTime == undefined) {
        return "";
      }
      return moment(dateTime).format("YYYY-MM-DD HH:mm:ss");
    },
    cleanSearch() {
      this.searchRuleName = null;
      this.searchCrawlDate = [];
    },
    deleteRule(id) {
      this.$confirm("此操作将删除该规则, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$fetch.apiWarning
            .deleteWaringRuleById({
              //查询参数
              id: id,
            })
            .then(({ data: data }) => {
              if (data == 1) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getWarningPageData();
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    runRule(id) {
      this.$confirm("是否运行该任务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => { 
          this.$fetch.apiWarning.runWaring({id}).then((res) => {
            console.log(res);
            if(res.status === 200) {
              if(res.data.code === 200) {
                this.$message.success("运行成功！")
              } else {
                this.$message.error("该规则正在运行中，请稍后再试！")
              }
            }
          }).catch(err => {
            this.$message.error("服务器错误")
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消运行",
          });
        });
    },
    updateRule(id) {
      this.$router.push({ name: "warningCreate", params: { id: id } });
    },
    // 改变自动运行
    changeAutoRun(data) {
      console.log(data)
      let obj = {}
      for(let key in data) {
        obj[key] = data[key]
      }
      obj.autoRun = Number(obj.autoRun)
      this.$fetch.apiWarning.addWaringRule(obj).then(res => {
        if(res.status === 200) {
          this.$message.success("更新状态成功！")
          this.getWarningPageData()
        } else {
          this.$message.error("服务器出现错误，更新失败！")
        }
      })
    }
  },
};
</script>

<style scoped>
.block {
  margin-top: 20px;
}
</style>
